package com.derbysoft.synxisadapter.commons.log;

import com.derbysoft.synxisadapter.commons.model.ReservationDetail;
import com.derbysoft.synxisadapter.commons.model.ReservationLog;
import com.derbysoft.synxisadapter.commons.repository.ReservationRepository;
import com.derbysoft.synxisadapter.commons.utils.XMLUtils;
import org.apache.commons.collections.CollectionUtils;

import java.util.Date;
import java.util.Set;

/**
 * User: jason
 * Date: 2012-12-03
 */
public class ReservationLogTask implements Runnable {

    private ReservationRepository reservationRepository;
    private ReservationPair reservationPair;
    private Set<LogDetailPair> logDetailPairs;

    public ReservationLogTask(ReservationRepository reservationRepository,
                              ReservationPair reservationPair, Set<LogDetailPair> logDetailPairs) {
        this.reservationRepository = reservationRepository;
        this.reservationPair = reservationPair;
        this.logDetailPairs = logDetailPairs;
    }

    @Override
    public void run() {
        saveLog();
    }

    private void saveLog() {
        Date timestamp = new Date();
        if (CollectionUtils.isNotEmpty(logDetailPairs)) {
            for (LogDetailPair logDetailPair : logDetailPairs) {
                for (Object otaObject : logDetailPair.getOtaObjects()) {
                    reservationPair.getReservationLog().appendDetail(createReservationDetail(otaObject, timestamp, reservationPair.getReservationLog()));
                }
            }
        }
        reservationRepository.update(reservationPair);
    }

    private ReservationDetail createReservationDetail(Object detail, Date timestamp, ReservationLog reservationLog) {
        ReservationDetail reservationDetail = new ReservationDetail();
        reservationDetail.setTimestamp(timestamp);
        reservationDetail.setDetail(XMLUtils.toXML(detail));
        reservationDetail.setReservationLog(reservationLog);
        return reservationDetail;
    }
}
